<!-- eslint-disable vue/no-mutating-props -->
<template>
  <a-table
    class="table"
    rowKey="id"
    :pagination="false"
    :scroll="{
      scrollToFirstRowOnChange: true,
      x: 'max-content',
    }"
    v-bind="props"
    :dataSource="data"
    :columns="
      props.columns.concat(
        canAdd && !disabled
          ? [
              {
                title: '操作',
                dataIndex: 'action',
                width: 50,
              },
            ]
          : []
      )
    "
    @resizeColumn="
        (w:number, col: ColumnItem) => {
          col.width = Math.max(w,col.minWidth||0);
        }
      "
  >
    <template
      #bodyCell="{
        column,
        record,
        index,
        text,
      }: {
        column: ColumnItem,
        record: Record<string, any>,
        index: number,
        text: any,
      }"
    >
      <a-button
        v-if="column.dataIndex === 'action'"
        type="link"
        style="padding: 0; height: auto"
        @click="handleDeleteClick(record)"
        >删除</a-button
      >
      <span v-else-if="column.dataIndex === 'index'">{{ index + 1 }}</span>
      <a-form-item-rest v-else-if="column.type">
        <span v-if="column.type === 'text'" v-bind="column.props">{{
          text
        }}</span>
        <component
          v-else
          :is="compMap[column.type] || 'a-' + column.type"
          v-model:value.trim="record[column.dataIndex || '']"
          :placeholder="`${column.type === 'select' ? '请选择' : '请填写'}${
            column.title
          }`"
          v-bind="column.props"
          :disabled="disabled"
        />
      </a-form-item-rest>
      <span v-else :title="text">{{ text }}</span>
    </template>
    <template #summary v-if="props.summary && sumData">
      <a-table-summary-row v-for="(row, rIndex) in props.summary" :key="rIndex">
        <a-table-summary-cell
          v-for="(col, cIndex) in row"
          :key="cIndex"
          v-bind="col.cellProps"
        >
          <span v-if="col.customRender">{{ col.customRender }}</span>
          <a-form-item-rest v-else-if="col.type">
            <component
              :is="compMap[col.type] || 'a-' + col.type"
              v-model:value.trim="sumData[col.dataIndex || '']"
              :placeholder="`${col.type === 'select' ? '请选择' : '请填写'}${
                col.title
              }`"
              v-bind="col.props"
              :disabled="disabled"
            />
          </a-form-item-rest>
        </a-table-summary-cell>
      </a-table-summary-row>
    </template>
  </a-table>
  <a-button
    v-if="canAdd && !disabled"
    block
    ghost
    type="primary"
    class="button-add"
    @click="handleAddClick"
    ><template #icon><plus-outlined class="icon-add" /></template
    >添加行</a-button
  >
</template>
<script lang="ts" setup>
import { provide, ref, watch } from "vue";
import { compMap } from "./config";
import { cloneDeep, debounce } from "lodash-es";
provide("isInTableComp", true);
const props = withDefaults(
  defineProps<{
    rowKey?: string;
    disabled?: boolean;
    value?: {
      dataSource: Record<string, any>[];
      summaryData: Record<string, any>;
    };
    columns: ColumnItem[];
    dataSource?: Record<string, any>[];
    placeholder?: string;
    style?: any;
    canAdd?: boolean;
    showHeader?: boolean;
    bordered?: boolean;
    summary?: summaryColumnItem[][];
    summaryData?: Record<string, any>;
  }>(),
  { showHeader: true }
);
const emit = defineEmits<{ (event: "update:value", value: any): void }>();
const data = ref(cloneDeep(props.value?.dataSource || props.dataSource) || []);
const sumData = ref(
  cloneDeep(props.value?.summaryData || props.summaryData) || {}
);
watch(
  [data, sumData],
  debounce(([val, sumVal]) => {
    if (
      !props.columns.find((col) =>
        val.find((item: any) => col.dataIndex && !item[col.dataIndex])
      ) &&
      !props.summary?.find((row) =>
        row.find((col) => col.dataIndex && !sumVal?.[col.dataIndex])
      )
    ) {
      emit("update:value", { dataSource: val, summaryData: sumVal });
    } else {
      emit("update:value", undefined);
    }
  }, 300),
  { deep: true }
);
const handleAddClick = () => {
  // const lastIndex = data.value.length - 1;
  // if (
  //   data.value.length === 0 ||
  //   data.value[lastIndex][
  //     props.columns.find((col) => !["index", "action"].includes(col.dataIndex))
  //       ?.dataIndex || ""
  //   ]
  // ) {
  data.value.push({
    [props.rowKey || "id"]: new Date().valueOf(),
  });
  // }
};
const handleDeleteClick = (record: Record<string, any>) => {
  data.value = data.value.filter(
    (item: Record<string, any>) =>
      item[props.rowKey || "id"] !== record[props.rowKey || "id"]
  );
};
</script>
<style lang="scss" scoped></style>
